package com.gf.framework.web.excel;

import com.alibaba.excel.EasyExcelFactory;
import com.gf.framework.web.annotation.ExportExcel;
import org.apache.commons.codec.CharEncoding;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author gaofei
 * @date 2022/6/8 21:38
 */
@Component
public class DefaultExportExcel implements IExportExcel{
    @Override
    public void export(HttpServletRequest request, HttpServletResponse response,
                       Type rawType, Type voType, Object result, ExportExcel exportExcel) throws IOException {
        if (rawType == List.class) {
            // 写入文件
            response.setContentType(getContentType());
            response.setCharacterEncoding(CharEncoding.UTF_8);
            response.setHeader("Content-disposition", "attachment;filename=".concat(URLEncoder.encode(exportExcel.fileName(), CharEncoding.UTF_8)).concat(".xlsx"));
            EasyExcelFactory.write(response.getOutputStream(), (Class<?>) voType)
                    .registerWriteHandler(new ExportExcelAspect.AdaptiveWidthStyleStrategy())
                    .sheet(exportExcel.sheetName())
                    .doWrite((List<?>) result);
        } else {
            throw new IllegalArgumentException("返回参数解析错误，导出方法返回值类型只能是List");
        }
    }

    @Override
    public String getContentType() {
        return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    }
}
